//
//  HomePageUserInfoViewController.m
//  ShowYork
//
//  Created by hxh on 2020/9/29.
//  Copyright © 2020 hxh. All rights reserved.
//

// 后期版本可能修改不同的高度所以有两个同样的宏
#define MINEHEADERHEIGHT (kNavStatusBarHeight + 332)
#define OTHERHEADERHEIGHT (kNavStatusBarHeight + 332)
#import "HomePageUserInfoViewController.h"
#import "HomePageUserInfoOpusListViewController.h"
#import "MineMessaeUnreadCountModel.h"
#import "MineMessageListViewController.h"
#import "HomePageUserDynamicListViewController.h"
#import "MineAccountUpdateDescViewController.h"
#import "LessonPageViewController.h"
#import "MineFollowListViewController.h"
#import "MineAccountSetViewController.h"
#import "HomePageUserInfoHeadView.h"
#import "HomePageRefreshHeader.h"
#import "HomePageUserInfoModel.h"
#import "MineFollowItemModel.h"
#import "UserInfoFollowModel.h"
@interface HomePageUserInfoViewController ()<HomePageUserInfoHeadViewDelegate>

@property (nonatomic,strong)UIImageView *backImgView;

@property (nonatomic,strong)UIButton *backBtn;

@property (nonatomic,strong)NSNumber *userId;

@property (nonatomic,strong)UIButton *followBtn;

@property (nonatomic,strong)HomePageUserInfoModel *currentModel;

@property (nonatomic,strong)UIImageView *noDataImgView;

@property (nonatomic,strong)UILabel *noDataLb;

@property (nonatomic,strong)CAGradientLayer *gradientLayer;

@property (nonatomic,strong)HomePageUserInfoHeadView *otherInfoHeaderView;

@property (nonatomic,strong)UIImageView *navIcon;

@property (nonatomic,assign)NSInteger totalLikeCount;

@property (nonatomic,assign)BOOL isNeedUpdate;

@end

@implementation HomePageUserInfoViewController


- (JXPagerView *)preferredPagingView {
    return [[JXPagerView alloc] initWithDelegate:self];
}

- (CAGradientLayer *)gradientLayer{
    if (!_gradientLayer) {
        _gradientLayer =  [CAGradientLayer layer];
        _gradientLayer.frame = self.followBtn.bounds;
        _gradientLayer.endPoint = CGPointMake(0, 0);
        _gradientLayer.startPoint = CGPointMake(1.0, 0);
        _gradientLayer.colors = @[(id)RGBA(247, 131, 97, 1).CGColor,(id)RGBA(245, 75, 100, 1).CGColor];
    }
    return _gradientLayer;
}

- (HomePageUserInfoHeadView *)otherInfoHeaderView{
    if (!_otherInfoHeaderView) {
        _otherInfoHeaderView = [[HomePageUserInfoHeadView alloc]init];
        _otherInfoHeaderView.delegate = self;
    }
    return _otherInfoHeaderView;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadUserInfo];
}
- (instancetype)initWithUserId:(NSNumber *)userId{
    if (self = [super init]) {
        self.userId = userId;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    [MobClick event:@"mine_user_show_total"];
    
    self.isHideNavBar = YES;
    
    if ([RPAppManager isShowNetworkView]) {
        @zf_weakify(self)
        [self showNetworkErrorWithNavTitle:@"" completeBlock:^{
           @zf_strongify(self)
            [self setUI];
            [self loadUserInfo];
        } cancelBlock:^{
            @zf_strongify(self)
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }else{
        [self setUI];
    }
    [self registNote];
}
- (void)setUI{
    
    self.isNeedUpdate = NO;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.pagerView = [self preferredPagingView];
    self.pagerView.mainTableView.gestureDelegate = self;
    self.pagerView.isListHorizontalScrollEnabled = YES;
    self.pagerView.automaticallyDisplayListVerticalScrollIndicator = NO;
    self.pagerView.pinSectionHeaderVerticalOffset = kNavBarHeight + 40;
    [self.view addSubview:self.pagerView];
    
    self.pagerView.frame = CGRectMake(0, 0, kScreenW, kScreenH);
    
    self.navIcon = [[UIImageView alloc]init];
    self.navIcon.layer.cornerRadius = 15;
    self.navIcon.layer.masksToBounds = YES;
    self.navIcon.alpha = 0;
    [self.view addSubview:self.navIcon];
    
    self.noDataLb = [[UILabel alloc]init];
    self.noDataLb.text = @"该用户已注销";
    self.noDataLb.textColor = C153;
    self.noDataLb.font = font(12);
    [self.view addSubview:self.noDataLb];
    
    self.noDataImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mine_noLogin_tag"]];
    [self.view addSubview:self.noDataImgView];
  

    self.followBtn = [[UIButton alloc]init];
    [self.followBtn setTitle:@"关注" forState:UIControlStateNormal];
    [self.followBtn addTarget:self action:@selector(doFollow) forControlEvents:UIControlEventTouchUpInside];
    self.followBtn.titleLabel.font = font(12);
    self.followBtn.layer.cornerRadius = 13;
    self.followBtn.layer.masksToBounds = YES;
    self.followBtn.hidden = YES;
    self.followBtn.backgroundColor = RGBA(224, 224, 224, 1);
    [self.view addSubview:self.followBtn];
    
    [self.followBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.navIcon);
        make.right.equalTo(self.view).offset(-16);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(26);
    }];
    
    
    self.backImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"common_back_tag"]];
    [self.view addSubview:self.backImgView];
    [self.backImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(16);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT + 12);
        
    }];
    self.backBtn = [[UIButton alloc]init];
    [self.backBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backBtn];
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.backImgView.mas_right).offset(16);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
        make.bottom.equalTo(self.backImgView.mas_bottom).offset(8);
    }];
    
    

    [self.noDataImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view).offset(-44);
    }];

    [self.noDataLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.noDataImgView.mas_bottom).offset(12);
    }];
    
    [self.navIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.backImgView);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    
    self.noDataImgView.hidden = YES;
    self.noDataLb.hidden = YES;
   
    self.view.backgroundColor = [UIColor whiteColor];
    self.pagerView.listContainerView.backgroundColor = [UIColor whiteColor];
    self.pagerView.mainTableView.backgroundColor = [UIColor whiteColor];
    self.otherInfoHeaderView.contentScrollView = self.pagerView.listContainerView.scrollView;


}

- (void)loadUserInfo{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"postId"] = self.userId.intValue == 0?[RPAppManager getCustomerId]:self.userId;
    if ([RPAppManager getCustomerId].intValue != 0) {
        param[@"userId"] = [RPAppManager getCustomerId];
    }
    param[@"md5"] = [RPAppManager md5StrWithApi:GetTopInfo];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetTopInfo) parames:param success:^(id responseObj) {
        HomePageUserInfoModel *model = [HomePageUserInfoModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        self.currentModel = model;
        self.userId = self.currentModel.userId;
        [self loadLikeListSource];
    } failure:^(NSError *error) {
       
    }];
}

- (void)loadLikeListSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"postId"] = self.userId;
    param[@"pageIndex"] = @(1);
    param[@"pageSize"] = @20;
    param[@"type"] = @"2";
    param[@"checked"] = @(1);
    param[@"md5"] = [RPAppManager md5StrWithApi:GetUserPostList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetUserPostList) parames:param success:^(id responseObj) {
        self.totalLikeCount = [responseObj[RESPONSE][TOTAL] intValue];
        [self loadUpdateUserInfo];
    } failure:^(id error) {
        
    }];
}

- (void)loadUpdateUserInfo{
    if (self.currentModel.imagePath.length != 0) {
        [self.navIcon sd_setImageWithURL:[NSURL URLWithString:self.currentModel.imagePath]];
    }else{
        if (self.currentModel.sex.intValue == 0) {
            self.navIcon.image = [UIImage imageNamed:@"defaut_header"];
        }else if (self.currentModel.sex.intValue == 1){
            self.navIcon.image = [UIImage imageNamed:@"common_boy_tag"];
        }else{
            self.navIcon.image = [UIImage imageNamed:@"common_girl_tag"];
        }
    }
   
    [self.otherInfoHeaderView setModel:self.currentModel];
    [self.otherInfoHeaderView updateHeaderLikedCount:self.totalLikeCount];
    
    
    if (self.currentModel != nil && [[RPAppManager getCustomerId] isEqualToNumber:self.currentModel.userId]) {
        self.userId = self.currentModel.userId;
    }else{
        if (self.currentModel.followType.intValue == 3) {
            [self.followBtn setTitle:@"互相关注" forState:UIControlStateNormal];
            [self.gradientLayer removeFromSuperlayer];
         
        }else if (self.currentModel.followType.intValue == 2){
            [self.followBtn setTitle:@"+ 回关" forState:UIControlStateNormal];
            [self.followBtn.layer insertSublayer:self.gradientLayer atIndex:0];
        }else if (self.currentModel.followType.intValue == 1){
            [self.followBtn setTitle:@"已关注" forState:UIControlStateNormal];
            [self.gradientLayer removeFromSuperlayer];
        }else{
            [self.followBtn setTitle:@"+ 关注" forState:UIControlStateNormal];
            [self.followBtn.layer insertSublayer:self.gradientLayer atIndex:0];
        }
    }
 
    
    if (self.currentModel.isDeleted || self.currentModel.deleted) {
        self.backImgView.image = [UIImage imageNamed:@"common_back_tag"];
        self.backImgView.hidden = NO;
        self.backBtn.hidden = NO;
        self.noDataImgView.hidden = NO;
        self.noDataLb.hidden = NO;
        [self.pagerView reloadData];
    }
    
}
- (void)registNote{
    // 游客模式切换登录模式
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:@"updateLoginUserInfoFollowListStatus" object:nil];
}

- (void)loginSuccess{
    //通知全局刷新
    self.isNeedUpdate = YES;
}

- (void)backMethod{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)doFollow{
    
    if (self.currentModel == nil) {
        return;
    }
    
    if (self.currentModel.followType.intValue == 3 || self.currentModel.followType.intValue == 1) {
        [self doFollowWithStatus:YES];
    }else{
        [self doFollowWithStatus:NO];
    }
}
- (void)messageMethod{
    MineMessageListViewController *listVC = [[MineMessageListViewController alloc]init];
    [self.navigationController pushViewController:listVC animated:YES];
}
- (void)setMethod{
    MineAccountSetViewController *setVC = [[MineAccountSetViewController alloc]init];
    [self.navigationController pushViewController:setVC animated:YES];
    __weak typeof(self)weakSelf = self;
    setVC.refresh = ^{
        UserInfoModel *userInfo = [UserInfoModel userInfo];
        weakSelf.currentModel.realName = userInfo.realName;
        weakSelf.currentModel.sex = userInfo.sex;
    };
}

#pragma mark - JXPagerMainTableViewGestureDelegate
- (BOOL)mainTableViewGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    //禁止categoryView左右滑动的时候，上下和左右都可以滚动
    return [gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && [otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]];
}
#pragma mark - JXPagerViewDelegate

- (UIView *)tableHeaderViewInPagerView:(JXPagerView *)pagerView {
    if (!(self.currentModel.isDeleted || self.currentModel.deleted)) {
        return self.otherInfoHeaderView;
    }
    return [UIView new];
}

- (NSUInteger)tableHeaderViewHeightInPagerView:(JXPagerView *)pagerView {
    
    if (self.currentModel.isDeleted || self.currentModel.deleted) {
        return 0;
    }else{
        return [[RPAppManager getCustomerId] isEqualToNumber:self.userId]?MINEHEADERHEIGHT:OTHERHEADERHEIGHT;
    }
}
- (NSUInteger)heightForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return 0;
}

- (UIView *)viewForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return [UIView new];
}
- (NSInteger)numberOfListsInPagerView:(JXPagerView *)pagerView {
    return (self.currentModel.isDeleted || self.currentModel.deleted)?0:2;
}

- (id<JXPagerViewListViewDelegate>)pagerView:(JXPagerView *)pagerView initListAtIndex:(NSInteger)index {
    __weak typeof(self)weakSelf = self;
    if (index == 1) {
        HomePageUserInfoOpusListViewController *likeVC = [[HomePageUserInfoOpusListViewController alloc]init];
        likeVC.userId = self.userId;
        return likeVC;
    }else{
        HomePageUserDynamicListViewController *dtlVC = [[HomePageUserDynamicListViewController alloc]init];
        dtlVC.userId = self.userId;
            dtlVC.updateItemCount = ^(NSInteger count) {
            [weakSelf.otherInfoHeaderView updateHeaderDynamicCount:count];
        };
        return dtlVC;
    }
}

- (void)pagerView:(JXPagerView *)pagerView mainTableViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y <= 0) {
        scrollView.contentOffset = CGPointMake(0, 0);
    }
    CGFloat height = [[RPAppManager getCustomerId] isEqualToNumber:self.userId]?MINEHEADERHEIGHT:OTHERHEADERHEIGHT;
    CGFloat alpha = scrollView.contentOffset.y/(height - (40 + kNavBarHeight));
    CGFloat alpha1 = 0;
    if (1-alpha <= 0) {
        alpha1 = scrollView.contentOffset.y/(height - (40 + kNavBarHeight));
    }
    if (alpha1 == 0) {
        self.backImgView.hidden = YES;
        self.followBtn.hidden = YES;
        self.navIcon.alpha = 0;
    }else{
        if (self.currentModel != nil && [[RPAppManager getCustomerId] isEqualToNumber:self.currentModel.userId]) {
          
        }else{
            self.followBtn.hidden = NO;
        }
        self.navIcon.alpha = 1;
        self.backImgView.hidden = NO;
    }
    if (scrollView.contentOffset.y <= 0) {
        if (self.currentModel != nil && [[RPAppManager getCustomerId] isEqualToNumber:self.currentModel.userId]) {

        }
        self.backImgView.hidden = NO;
    }

    [self.otherInfoHeaderView updateHeaderViewAlpha:1-alpha otherViewAlpha:alpha1];
}

#pragma mark - HomePageUserInfoHeadViewDelegate

- (void)doFollowWithStatus:(BOOL)status{
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
    if (self.currentModel.followType.intValue == 1) {
        [MobClick event:@"mine_user_cancel_follow_click"];
    }else if (self.currentModel.followType.intValue == 2){
        [MobClick event:@"mine_user_follow_back_click"];
    }else if (self.currentModel.followType.intValue == 0){
        [MobClick event:@"mine_user_follow_click"];
    }
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"followId"] = self.currentModel.userId;
    param[@"type"] = status?@(2):@(1);
    param[@"md5"] = [RPAppManager md5StrWithApi:FollowAndUnFollow];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(FollowAndUnFollow) parames:param success:^(id responseObj) {
        
        if (status) {
            [WHToast showMessage:@"取消关注" duration:2 finishHandler:nil];
        }else{
            [WHToast showMessage:@"关注成功" duration:2 finishHandler:nil];
        }
        
        self.currentModel.followType = responseObj[RESPONSE][@"followCode"];
        
        MineFollowItemModel *itemModel = [MineFollowItemModel new];
        
        itemModel.followCode = self.currentModel.followType;
        
        itemModel.userId = self.currentModel.userId;
        
        [self.otherInfoHeaderView setModel:self.currentModel];
        
        if (self.currentModel.followType.intValue == 3) {
            [self.followBtn setTitle:@"互相关注" forState:UIControlStateNormal];
            [self.gradientLayer removeFromSuperlayer];
         
        }else if (self.currentModel.followType.intValue == 2){
            [self.followBtn setTitle:@"+ 回关" forState:UIControlStateNormal];
            [self.followBtn.layer insertSublayer:self.gradientLayer atIndex:0];
        }else if (self.currentModel.followType.intValue == 1){
            [self.followBtn setTitle:@"已关注" forState:UIControlStateNormal];
            [self.gradientLayer removeFromSuperlayer];
        }else{
            [self.followBtn setTitle:@"+ 关注" forState:UIControlStateNormal];
            [self.followBtn.layer insertSublayer:self.gradientLayer atIndex:0];
        }
        
        MineFollowItemModel *model = [[MineFollowItemModel alloc]init];
        model.followCode = self.currentModel.followType;
        model.userId = self.currentModel.userId;
        
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"updateUserInfoFollowListStatus" object:nil userInfo:@{@"data":model}];
        
        __block BOOL isLocal = NO;
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm transactionWithBlock:^{
            RLMResults<UserInfoFollowModel *> *result = [UserInfoFollowModel allObjects];
            if (result.count > 0) {
                for (int index = 0; index < result.count; index++) {
                    UserInfoFollowModel *itemModel = result[index];
                    if (itemModel.userId == self.currentModel.userId.longValue) {
                        itemModel.followCode = self.currentModel.followType.longValue;
                        isLocal = YES;
                        break;
                    }
                }
            }
            if (!isLocal) {
                UserInfoFollowModel *userInfo = [[UserInfoFollowModel alloc]init];
                userInfo.userId = self.currentModel.userId.longValue;
                userInfo.followCode = self.currentModel.followType.longValue;
                userInfo.realName = self.currentModel.realName;
                [realm addOrUpdateObject:userInfo];
            }
        }];
        
        //隐藏按钮
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

- (void)getUserInfodynamicList{
    [self.pagerView.listContainerView.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];

    [self.pagerView.listContainerView didClickSelectedItemAtIndex:0];
}
- (void)getUserInfoLikedList{
   
    [self.pagerView.listContainerView.scrollView setContentOffset:CGPointMake(kScreenW, 0) animated:YES];

    [self.pagerView.listContainerView didClickSelectedItemAtIndex:1];
    
}

@end
